package com.yyh.synctool.server.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author xuan
 * @create 2021/12/18
 */
public class MD5Utils
{
    private static final String CHAR_ENCODING = "UTF-8";

    /** 对密码进行 MD5 1024次散列 */
    public static String getMd5Password(String password, String salt) {
        return getMd5Password(password, salt, 1024);
    }

    private static String getMd5Password(String password, String salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            if (null != salt) {
                // 加盐，相当于拼接  ==> password = salt + password;
                digest.update(salt.getBytes(CHAR_ENCODING));
            }

            // 散列一次的结果
            byte[] hashed = digest.digest(password.getBytes(CHAR_ENCODING));
            int hashIterations = iterations - 1;

            for (int i = 0; i < hashIterations; i++) {
                digest.reset();
                hashed = digest.digest(hashed);
            }

            return bytesToHex(hashed);

        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
